package com.glowdayz.glowmee.bc;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.glowdayz.common.DBHandler;
import com.glowdayz.common.MultipartBox.FileInfo;
import com.glowdayz.glowmee.cmd.RegisterCMD;
import com.glowdayz.glowmee.dao.RegisterDAO;

public class UpdateRegisterBC extends HttpServlet {
	
	private static final long serialVersionUID = 1L;
       
    public UpdateRegisterBC() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DBHandler.getInstance().connect();
		
		request.setCharacterEncoding("utf-8");
		
		int idRegister = Integer.parseInt(request.getParameter("id"));
		
		try {
			RegisterCMD cmd = RegisterDAO.getInstance().getRegister(idRegister);
			
			FileInfo image = cmd.getImage();
			if (image != null) {
				request.setAttribute("image", image);
			}
			request.setAttribute("cmd", cmd);
		} catch (Exception e) {
			DBHandler.getInstance().disconnect();
			e.printStackTrace();
		}
		
		DBHandler.getInstance().disconnect();
		RequestDispatcher dpr = request.getRequestDispatcher("/register/updateRegister.jsp");
		dpr.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		DBHandler.getInstance().connect();
		
		request.setCharacterEncoding("utf-8");
		
		int isActivity = Integer.parseInt(request.getParameter("isActivity"));
		int idRegister = Integer.parseInt(request.getParameter("idRegister"));
		
		// 삭제할 파일에 대한 체크상태값
		String[] delete_file = request.getParameterValues("imgDelete");
		
		try {
			RegisterDAO.getInstance().updateRegisterOfAdmin(new RegisterCMD(idRegister, isActivity), delete_file);
			RegisterCMD cmd = RegisterDAO.getInstance().getRegister(idRegister);
			
			FileInfo image = cmd.getImage();
			if (image != null) {
				request.setAttribute("image", image);
			}
			request.setAttribute("cmd", cmd);
			request.setAttribute("alert", "<script type='text/javascript'>alert('수정이 완료되었습니다.')</script>");
		} catch (Exception e) {
			DBHandler.getInstance().disconnect();
			e.printStackTrace();
		}
		
		DBHandler.getInstance().disconnect();
		RequestDispatcher dpr = request.getRequestDispatcher("/register/updateRegister.jsp");
		dpr.forward(request, response);
		
	}

}